import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: 'http://121.4.190.32:8080',
  // baseURL: 'http://192.168.1.113:8080', // dev
  // baseURL: 'http://localhost:8080',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 8000, // request timeout
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== '00000') {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      // if the custom code is not 20000, it is judged as an error.
      if (res.code === '201') {
        MessageBox.confirm('您已登出，您可以取消停留在此页面，或重新登录', '确认登出', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
        return res
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log(error.response)
    const { status, data } = error.response
    console.log(status, data)
    // const errCode = JSON.stringify(response.data.code)
    if (status === 500) {
      MessageBox.confirm(`${data.message}`, '错误提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (data.code !== '201') {
          Message({
            message: data.message,
            type: 'error',
            duration: 5 * 1000
          })
        } else {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }
      }).catch(() => {
        Message({
          message: '已取消',
          type: 'error',
          duration: 1 * 1000
        })
      })
      // if (error) {
      //   // Message({
      //   //   message: resData,
      //   //   type: 'error',
      //   //   duration: 5 * 1000
      //   // })
      //   // console.log(response.status)
      // }
    }
    return Promise.reject(error)
  }
)

export default service
